<?php

namespace App\Http\Controllers\v1;

use App\Http\Resources\ClassesCollection;
use App\Models\Classes;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ClassesController extends Controller
{
    /**
     * 课时列表
     * 可选参数 offset偏移量 limit条数 关键字kw
     * 按照更新时间倒序排列
     * @param Request $request
     * @return ClassesCollection
     */
    public function index(Request $request)
    {
//        偏移量
        $offset = $request->get('offset', 0);
//        条数
        $limit = $request->get('limit', 5);
//        条数限制
        $limit = min(max($limit, 1), 20);
//        kw
        $kw = $request->get('kw');
        $data = Classes::limit($limit)
            ->with(['category', 'course'])
            ->where('name', 'LIKE', '%' . $kw . '%')
            ->offset($offset)
            ->orderBy('updated_at', 'desc')
            ->get();
        return new ClassesCollection($data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * 课时详情
     *
     * @param  int $id
     * @return \App\Http\Resources\Classes
     */
    public function show(int $id)
    {
        $data = Classes::with(['category', 'course'])->find($id);
        return new \App\Http\Resources\Classes($data);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /**
     * 播放次数自增
     * @param int $id 课时ID
     * @return \Illuminate\Http\JsonResponse
     */
    public function countIncrement(int $id)
    {
        $res = Classes::where('id', $id)->increment('count');
        if ($res) return response()->json(['status' => 0, 'msg' => '成功']);
        return response()->json(['status' => 1, 'msg' => '失败']);
    }
}
